// 用户管理路由
const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const { query, transaction } = require('../config/database');
const { authenticateToken, requireAdmin } = require('../middleware/auth');
const { validateId, validatePagination, validateRecharge } = require('../middleware/validation');
const { calculatePagination, hashPassword, formatAmount } = require('../utils/helpers');
const ResponseHelper = require('../utils/response');

// 图片安全检查函数
const isValidImageFile = (filePath) => {
  try {
    const buffer = fs.readFileSync(filePath);

    // 检查文件头部魔数
    const magicNumbers = {
      'jpeg': [0xFF, 0xD8, 0xFF],
      'png': [0x89, 0x50, 0x4E, 0x47],
      'gif': [0x47, 0x49, 0x46],
      'webp': [0x52, 0x49, 0x46, 0x46] // RIFF
    };

    for (const [format, magic] of Object.entries(magicNumbers)) {
      if (magic.every((byte, index) => buffer[index] === byte)) {
        return true;
      }
    }

    return false;
  } catch (error) {
    console.error('文件验证错误:', error);
    return false;
  }
};

// 生成安全的文件名
const generateSecureFilename = (originalname) => {
  const ext = path.extname(originalname).toLowerCase();
  const timestamp = Date.now();
  const randomBytes = crypto.randomBytes(8).toString('hex');
  return `avatar-${timestamp}-${randomBytes}${ext}`;
};

// 配置文件上传
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = process.env.UPLOAD_PATH || './uploads';
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const secureFilename = generateSecureFilename(file.originalname);
    cb(null, secureFilename);
  }
});

const upload = multer({
  storage,
  limits: {
    fileSize: parseInt(process.env.MAX_FILE_SIZE) || 10 * 1024 * 1024 // 10MB
  },
  fileFilter: (req, file, cb) => {
    // 支持更多图片格式，包括WebP
    const allowedTypes = /jpeg|jpg|png|gif|webp/;
    const allowedMimeTypes = /image\/(jpeg|jpg|png|gif|webp)/;

    const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = allowedMimeTypes.test(file.mimetype);

    if (mimetype && extname) {
      return cb(null, true);
    } else {
      cb(new Error('只允许上传图片文件 (支持 JPG、PNG、GIF、WebP 格式)'));
    }
  }
});

// 获取用户个人信息
router.get('/profile', authenticateToken, async (req, res) => {
  try {
    const user = req.user;

    ResponseHelper.success(res, user, '获取个人信息成功');

  } catch (error) {
    console.error('获取个人信息错误:', error);
    ResponseHelper.serverError(res, '获取个人信息失败');
  }
});

// 更新用户个人信息
router.put('/profile', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { username, email, real_name } = req.body;

    // 检查用户名是否已被其他用户使用
    if (username) {
      const existingUsers = await query(
        'SELECT id FROM users WHERE username = ? AND id != ?',
        [username, userId]
      );

      if (existingUsers.length > 0) {
        return ResponseHelper.error(res, '用户名已被使用', 400);
      }
    }

    // 更新用户信息
    await query(
      'UPDATE users SET username = ?, email = ?, real_name = ?, updated_at = NOW() WHERE id = ?',
      [username || req.user.username, email || req.user.email, real_name || req.user.real_name, userId]
    );

    // 获取更新后的用户信息
    const updatedUsers = await query(
      'SELECT id, username, phone, email, real_name, role, status, balance, play_time, avatar, created_at FROM users WHERE id = ?',
      [userId]
    );

    ResponseHelper.success(res, updatedUsers[0], '个人信息更新成功');

  } catch (error) {
    console.error('更新个人信息错误:', error);
    ResponseHelper.serverError(res, '更新个人信息失败');
  }
});

// 上传头像
router.post('/avatar', authenticateToken, upload.single('avatar'), async (req, res) => {
  try {
    console.log('📤 收到头像上传请求:', {
      userId: req.user.id,
      file: req.file ? {
        originalname: req.file.originalname,
        mimetype: req.file.mimetype,
        size: req.file.size,
        filename: req.file.filename
      } : null
    });

    if (!req.file) {
      console.error('❌ 没有收到文件');
      return ResponseHelper.error(res, '请选择要上传的头像文件', 400);
    }

    const userId = req.user.id;
    const uploadedFilePath = req.file.path;
    const avatarPath = `/uploads/${req.file.filename}`;

    console.log('📁 头像文件保存路径:', avatarPath);

    // 安全检查：验证文件是否为真实的图片文件
    if (!isValidImageFile(uploadedFilePath)) {
      // 删除无效文件
      if (fs.existsSync(uploadedFilePath)) {
        fs.unlinkSync(uploadedFilePath);
      }
      console.error('❌ 文件安全检查失败');
      return ResponseHelper.error(res, '上传的文件不是有效的图片格式', 400);
    }

    // 删除旧头像文件
    if (req.user.avatar) {
      const oldAvatarPath = path.join(process.cwd(), req.user.avatar);
      if (fs.existsSync(oldAvatarPath)) {
        fs.unlinkSync(oldAvatarPath);
        console.log('🗑️ 已删除旧头像文件:', oldAvatarPath);
      }
    }

    // 更新数据库中的头像路径
    await query(
      'UPDATE users SET avatar = ?, updated_at = NOW() WHERE id = ?',
      [avatarPath, userId]
    );

    console.log('✅ 头像上传成功:', avatarPath);

    ResponseHelper.success(res, {
      avatar: avatarPath
    }, '头像上传成功');

  } catch (error) {
    console.error('❌ 头像上传错误:', error);

    // 清理上传失败的文件
    if (req.file && req.file.path && fs.existsSync(req.file.path)) {
      try {
        fs.unlinkSync(req.file.path);
        console.log('🗑️ 已清理上传失败的文件:', req.file.path);
      } catch (cleanupError) {
        console.error('清理文件失败:', cleanupError);
      }
    }

    ResponseHelper.serverError(res, '头像上传失败');
  }
});

// 修改密码
router.put('/password', authenticateToken, async (req, res) => {
  try {
    const { currentPassword, newPassword } = req.body;

    if (!currentPassword || !newPassword) {
      return ResponseHelper.error(res, '当前密码和新密码不能为空', 400);
    }

    if (newPassword.length < 6 || newPassword.length > 20) {
      return ResponseHelper.error(res, '新密码长度必须在6-20个字符之间', 400);
    }

    const userId = req.user.id;

    // 获取当前密码
    const users = await query('SELECT password FROM users WHERE id = ?', [userId]);
    if (users.length === 0) {
      return ResponseHelper.error(res, '用户不存在', 404);
    }

    // 验证当前密码
    const { comparePassword } = require('../utils/helpers');
    const isCurrentPasswordValid = await comparePassword(currentPassword, users[0].password);
    if (!isCurrentPasswordValid) {
      return ResponseHelper.error(res, '当前密码错误', 400);
    }

    // 加密新密码
    const hashedNewPassword = await hashPassword(newPassword);

    // 更新密码
    await query(
      'UPDATE users SET password = ?, updated_at = NOW() WHERE id = ?',
      [hashedNewPassword, userId]
    );

    ResponseHelper.success(res, null, '密码修改成功');

  } catch (error) {
    console.error('修改密码错误:', error);
    ResponseHelper.serverError(res, '修改密码失败');
  }
});

// 获取用户余额
router.get('/balance', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;

    const users = await query('SELECT balance FROM users WHERE id = ?', [userId]);
    if (users.length === 0) {
      return ResponseHelper.error(res, '用户不存在', 404);
    }

    ResponseHelper.success(res, {
      balance: formatAmount(users[0].balance)
    }, '获取余额成功');

  } catch (error) {
    console.error('获取余额错误:', error);
    ResponseHelper.serverError(res, '获取余额失败');
  }
});

// 账户充值
router.post('/recharge', authenticateToken, validateRecharge, async (req, res) => {
  try {
    const userId = req.user.id;
    const { amount, payment_method, remark } = req.body;

    await transaction(async (connection) => {
      // 更新用户余额
      await connection.execute(
        'UPDATE users SET balance = balance + ?, updated_at = NOW() WHERE id = ?',
        [amount, userId]
      );

      // 记录充值记录
      await connection.execute(
        `INSERT INTO recharge_records (user_id, amount, payment_method, status, remark, created_at)
         VALUES (?, ?, ?, 'completed', ?, NOW())`,
        [userId, amount, payment_method, remark || '']
      );
    });

    // 获取更新后的余额
    const users = await query('SELECT balance FROM users WHERE id = ?', [userId]);

    ResponseHelper.success(res, {
      balance: formatAmount(users[0].balance),
      recharge_amount: formatAmount(amount),
      totalAmount: formatAmount(amount)  // 前端期望的字段名
    }, '充值成功');

  } catch (error) {
    console.error('账户充值错误:', error);
    ResponseHelper.serverError(res, '充值失败，请稍后重试');
  }
});

// 获取充值记录
router.get('/recharge/history', authenticateToken, validatePagination, async (req, res) => {
  try {
    const userId = req.user.id;
    const { page, pageSize, offset, limit } = calculatePagination(req.query.page, req.query.pageSize);

    // 获取充值记录总数
    const countResult = await query(
      'SELECT COUNT(*) as total FROM recharge_records WHERE user_id = ?',
      [userId]
    );
    const total = countResult[0].total;

    // 获取充值记录列表
    const records = await query(
      `SELECT id, amount, payment_method, status, remark, created_at
       FROM recharge_records
       WHERE user_id = ?
       ORDER BY created_at DESC
       LIMIT ? OFFSET ?`,
      [userId, limit, offset]
    );

    ResponseHelper.paginated(res, records, total, page, pageSize, '获取充值记录成功');

  } catch (error) {
    console.error('获取充值记录错误:', error);
    ResponseHelper.serverError(res, '获取充值记录失败');
  }
});

// 获取用户设置
router.get('/settings', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;

    // 这里可以从数据库获取用户设置，暂时返回默认设置
    const settings = {
      notifications: {
        email: true,
        sms: false,
        push: true
      },
      privacy: {
        showPhone: false,
        showEmail: false
      },
      preferences: {
        language: 'zh-CN',
        theme: 'light'
      }
    };

    ResponseHelper.success(res, settings, '获取用户设置成功');

  } catch (error) {
    console.error('获取用户设置错误:', error);
    ResponseHelper.serverError(res, '获取用户设置失败');
  }
});

// 更新用户设置
router.put('/settings', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const settings = req.body;

    // 这里可以将设置保存到数据库，暂时只返回成功响应
    console.log(`用户 ${userId} 更新设置:`, settings);

    ResponseHelper.success(res, settings, '用户设置更新成功');

  } catch (error) {
    console.error('更新用户设置错误:', error);
    ResponseHelper.serverError(res, '更新用户设置失败');
  }
});

module.exports = router;
